package com.kate.mall.oauth.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kate.mall.common.utils.ListMap2VoUtil;
import com.kate.mall.common.utils.R;
import com.kate.mall.oauth.constant.MessageConstant;
import com.kate.mall.oauth.dto.ClientDto;
import com.kate.mall.oauth.dto.SecurityUser;
import com.kate.mall.oauth.dto.UserDTO;
import com.kate.mall.oauth.feign.MemeberFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 用户管理业务类
 * @Auther: 新梦想*陈超
 * @Date: 2021/8/12 17:26
 * Java : 对象       (女朋友)
 * Student stu =new Student();  1.实例化
 * sut.name="二狗子"             2.给属性赋值
 *
 * Spring :Bean     （老婆---1.订婚  2.领证  3.结婚 4.办酒）
 *      Student stu =new Student();  1.实例化
 *      sut.name="二狗子"             2.给属性赋值
 *      init();                      3.初始化
 *      destroy();                   4.销毁
 *
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    private List<UserDTO> userList;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Resource
    private MemeberFeignClient memeberFeignClient;

    @Resource
    private ListMap2VoUtil listMap2VoUtil;

    @Resource
    private ObjectMapper objectMapper;


    @PostConstruct /*spring 中bean的生命周期 ：1.实例化 2.属性赋值  2.bean初始化方法 3.销毁 */
    public void initData() {
        /*TODO 从内存中获取用户信息(用户名、密码、角色)*/
        String password = passwordEncoder.encode("123456");
        System.out.println("password(openid)===>"+password);
        System.out.println("password(123456)===>"+passwordEncoder.encode("oJrMh5S5mrUO5WYoRLXtx0rX70_Y"));
        userList = new ArrayList<>();
        userList.add(new UserDTO(1,"kate", password,1, CollUtil.toList("ADMIN")));
        userList.add(new UserDTO(2,"andy", password,1, CollUtil.toList("TEST")));
        /*TODO 从数据中获取用户信息(用户名、密码、角色)*/

    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //List<UserDTO> findUserList = userList.stream().filter(item -> item.getUsername().equals(username)).collect(Collectors.toList());
        //if (CollUtil.isEmpty(findUserList)) {
        //    throw new UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
        //}
        //SecurityUser securityUser = new SecurityUser(findUserList.get(0));
        /*TODO 集成到微商城中需要改为从数据库获取用户信息：两种用户 运营平台用户(ums_admin)和会员(ums_memeber)*/
        R userInfoR = memeberFeignClient.getUserInfoByName(username);
        List<Map> userInfoMapList = MapUtil.get((Map)userInfoR.get("page"),"list",List.class);
        List<UserDTO> userDtoList = listMap2VoUtil.<UserDTO>map2vo(userInfoMapList, UserDTO.class);
        userDtoList = objectMapper.convertValue(userDtoList,new TypeReference<List<UserDTO>>(){});
        if (CollUtil.isEmpty(userDtoList)) {
            throw new UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
        }
        SecurityUser securityUser = new SecurityUser(userDtoList.get(0).setRoles(CollUtil.toList("TEST")));
        if (!securityUser.isEnabled()) {
            throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
        } else if (!securityUser.isAccountNonLocked()) {
            throw new LockedException(MessageConstant.ACCOUNT_LOCKED);
        } else if (!securityUser.isAccountNonExpired()) {
            throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
        } else if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
        }
        return securityUser;
    }

}